package com.yumei.trader.gym.page;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yumei.trader.gym.act.SLTraderAct;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.yumei.trader.gym.R;
import com.yumei.trader.gym.act.TraderAct;
import com.yumei.trader.gym.client.TGApplication;
import com.yumei.trader.gym.dbase.DBaseConst;
import com.yumei.trader.gym.dbase.sqlite.SqliteActObject;
import com.yumei.trader.gym.object.ActObj;
import com.yumei.trader.gym.object.GameMapObj;
import com.yumei.trader.gym.raw.GameSoundManager;
import com.yumei.trader.gym.raw.TradeSoundPool;
import com.yumei.trader.gym.util.StringUtils;
import com.yumei.trader.gym.view.AnalyzeManager;
import com.yumei.trader.gym.view.StockConst;
import com.yumei.trader.gym.view.StockRequest;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Random;
import java.util.zip.Inflater;

public class PageGamePlay extends PlayerBase {

    //暂停面板
    private View layoutPause;
    //暂停子面板
    private View[] pausePanels = new View[2];

    private ImageButton btnInfo, btnTime;
    private ImageView centerImg, bottomImg;

    private LinearLayout[] indexLayouts = new LinearLayout[7];
    private TextView[] indexTxts = new TextView[7];
    private ImageView[] indexImages = new ImageView[7];

    private LinearLayout[] timeLayouts = new LinearLayout[5];
    private TextView[] timeTxts = new TextView[5];
    private ImageView[] timeImages = new ImageView[5];

    //速度数组
    private static final int[] slowLabel = {1000, 2000, 3000, 4000, 5000};
    private static final int[] stockIndex = {StockConst.Index_Up_BOLL, StockConst.Index_Up_MA,
            StockConst.Index_Up_SAR, StockConst.Index_Down_MACD,
            StockConst.Index_Down_DMI, StockConst.Index_Down_RSI, StockConst.Index_Down_KDJ
    };

    private GameMapObj gameInfo = new GameMapObj();
    private TGApplication mApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //界面全屏，隐藏状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mApp = (TGApplication) this.getApplication();
        this.setContentView(R.layout.page_game_play);

        transparentBar();
        registerBaseComponent();
        registerComponent();

        mAccount = new SLTraderAct(this);
        mAccount.reset();
        this.setAccount(mAccount);

        loadStockHisData();
    }

    private void registerComponent() {

        final String speed = mApp.getDBMrg().getValue(DBaseConst.Trade_Speed, "1");
        int speedIndex = Integer.parseInt(speed);
        THREAD_TIME = slowLabel[speedIndex];

        layoutPause = this.findViewById(R.id.layout_pause);
        layoutPause.setVisibility(View.GONE);

        //退出
        ImageButton btnExit = this.findViewById(R.id.btn_exit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                centerImg.setVisibility(View.INVISIBLE);
                bottomImg.setVisibility(View.INVISIBLE);
                showExitAlertDialog();
                onPauseAction(true);
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        //指标
        btnInfo = this.findViewById(R.id.btn_info);
        btnInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pausePanels[0].getVisibility() == View.VISIBLE) {
                    pausePanels[0].setVisibility(View.GONE);
                    btnInfo.setBackgroundResource(R.mipmap.ic_game_index_normal);
                    centerImg.setVisibility(View.GONE);
                    bottomImg.setVisibility(View.GONE);
                } else {
                    onShowPausePanel(0);
                    btnTime.setBackgroundResource(R.mipmap.ic_game_time_normal);
                    btnInfo.setBackgroundResource(R.mipmap.ic_game_index_pressed);
                    centerImg.setVisibility(View.VISIBLE);
                    bottomImg.setVisibility(View.GONE);
                }
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        //游戏速度
        btnTime = this.findViewById(R.id.btn_time);
        btnTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pausePanels[1].getVisibility() == View.VISIBLE) {
                    pausePanels[1].setVisibility(View.GONE);
                    btnTime.setBackgroundResource(R.mipmap.ic_game_time_normal);
                    centerImg.setVisibility(View.GONE);
                    bottomImg.setVisibility(View.GONE);
                } else {
                    onShowPausePanel(1);
                    btnInfo.setBackgroundResource(R.mipmap.ic_game_index_normal);
                    btnTime.setBackgroundResource(R.mipmap.ic_game_time_pressed);
                    centerImg.setVisibility(View.GONE);
                    bottomImg.setVisibility(View.VISIBLE);
                }
                playSound(TradeSoundPool.ACTION_BUTTON);
            }
        });

        pausePanels[0] = this.findViewById(R.id.layout_info);
        pausePanels[0].setVisibility(View.GONE);

        pausePanels[1] = this.findViewById(R.id.layout_time);
        pausePanels[1].setVisibility(View.GONE);

        centerImg = this.findViewById(R.id.game_play_horn_center);
        bottomImg = this.findViewById(R.id.game_play_horn_bottom);

        indexLayouts[0] = this.findViewById(R.id.game_play_index_01_layout);
        indexLayouts[0].setTag(0);
        indexLayouts[0].setOnClickListener(clickListener);
        indexTxts[0] = this.findViewById(R.id.game_play_index_01_txt);
        indexImages[0] = this.findViewById(R.id.game_play_index_01_img);

        indexLayouts[1] = this.findViewById(R.id.game_play_index_02_layout);
        indexLayouts[1].setTag(1);
        indexLayouts[1].setOnClickListener(clickListener);
        indexTxts[1] = this.findViewById(R.id.game_play_index_02_txt);
        indexImages[1] = this.findViewById(R.id.game_play_index_02_img);

        indexLayouts[2] = this.findViewById(R.id.game_play_index_03_layout);
        indexLayouts[2].setTag(2);
        indexLayouts[2].setOnClickListener(clickListener);
        indexTxts[2] = this.findViewById(R.id.game_play_index_03_txt);
        indexImages[2] = this.findViewById(R.id.game_play_index_03_img);

        indexLayouts[3] = this.findViewById(R.id.game_play_index_04_layout);
        indexLayouts[3].setTag(3);
        indexLayouts[3].setOnClickListener(clickListener);
        indexTxts[3] = this.findViewById(R.id.game_play_index_04_txt);
        indexImages[3] = this.findViewById(R.id.game_play_index_04_img);

        indexLayouts[4] = this.findViewById(R.id.game_play_index_05_layout);
        indexLayouts[4].setTag(4);
        indexLayouts[4].setOnClickListener(clickListener);
        indexTxts[4] = this.findViewById(R.id.game_play_index_05_txt);
        indexImages[4] = this.findViewById(R.id.game_play_index_05_img);

        indexLayouts[5] = this.findViewById(R.id.game_play_index_06_layout);
        indexLayouts[5].setTag(5);
        indexLayouts[5].setOnClickListener(clickListener);
        indexTxts[5] = this.findViewById(R.id.game_play_index_06_txt);
        indexImages[5] = this.findViewById(R.id.game_play_index_06_img);

        indexLayouts[6] = this.findViewById(R.id.game_play_index_07_layout);
        indexLayouts[6].setTag(6);
        indexLayouts[6].setOnClickListener(clickListener);
        indexTxts[6] = this.findViewById(R.id.game_play_index_07_txt);
        indexImages[6] = this.findViewById(R.id.game_play_index_07_img);

        timeLayouts[0] = this.findViewById(R.id.game_play_time_01_layout);
        timeLayouts[0].setTag(0);
        timeLayouts[0].setOnClickListener(timeClickListener);
        timeTxts[0] = this.findViewById(R.id.game_play_time_01_txt);
        timeImages[0] = this.findViewById(R.id.game_play_time_01_img);

        timeLayouts[1] = this.findViewById(R.id.game_play_time_02_layout);
        timeLayouts[1].setTag(1);
        timeLayouts[1].setOnClickListener(timeClickListener);
        timeTxts[1] = this.findViewById(R.id.game_play_time_02_txt);
        timeImages[1] = this.findViewById(R.id.game_play_time_02_img);

        timeLayouts[2] = this.findViewById(R.id.game_play_time_03_layout);
        timeLayouts[2].setTag(2);
        timeLayouts[2].setOnClickListener(timeClickListener);
        timeTxts[2] = this.findViewById(R.id.game_play_time_03_txt);
        timeImages[2] = this.findViewById(R.id.game_play_time_03_img);

        timeLayouts[3] = this.findViewById(R.id.game_play_time_04_layout);
        timeLayouts[3].setTag(3);
        timeLayouts[3].setOnClickListener(timeClickListener);
        timeTxts[3] = this.findViewById(R.id.game_play_time_04_txt);
        timeImages[3] = this.findViewById(R.id.game_play_time_04_img);

        timeLayouts[4] = this.findViewById(R.id.game_play_time_05_layout);
        timeLayouts[4].setTag(4);
        timeLayouts[4].setOnClickListener(timeClickListener);
        timeTxts[4] = this.findViewById(R.id.game_play_time_05_txt);
        timeImages[4] = this.findViewById(R.id.game_play_time_05_img);

        initUserSetting();
        changeTimeStyle(Integer.valueOf(speed));
    }

    /**
     * 加载用户指标设置
     */
    private void initUserSetting() {

        String upStr = mApp.getDBMrg().getValue(DBaseConst.Up_Index, "1");
        changeChooseStyle(0, 3, Integer.valueOf(upStr));
        String downStr = mApp.getDBMrg().getValue(DBaseConst.Down_Index, "3");
        changeChooseStyle(3, 7, Integer.valueOf(downStr));
        StockRequest.indexs = new int[]{stockIndex[Integer.parseInt(upStr)], stockIndex[Integer.parseInt(downStr)]};

        AnalyzeManager.getInstance().analyzeIndex(klineView.getDataSource(), mTask);
        int oldOffset = klineView.getOffset();
        klineView.setDataSource(klineView.getDataSource(), mTask);
        klineView.setOffset(oldOffset);
    }

    /**
     * 指标设置点击事件逻辑
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int tag = (int) v.getTag();

            if (tag < 3) {
                changeChooseStyle(0, 3, tag);
                mApp.getDBMrg().addParam(DBaseConst.Up_Index, String.valueOf(tag));
                mApp.getDBMrg().save();
            } else {
                changeChooseStyle(3, 7, tag);
                mApp.getDBMrg().addParam(DBaseConst.Down_Index, String.valueOf(tag));
                mApp.getDBMrg().save();
            }

            initUserSetting();
        }
    };

    /**
     * 更换指标显示样式
     *
     * @param startIndex 数组起始下标
     * @param endIndex   数组结束下标
     * @param tag        选中的下标
     */
    private void changeChooseStyle(int startIndex, int endIndex, int tag) {
        for (int i = startIndex; i < endIndex; i++) {
            indexImages[i].setVisibility(View.INVISIBLE);
            indexTxts[i].setTextColor(ContextCompat.getColor(this, R.color.color_game_normal));
        }
        indexImages[tag].setVisibility(View.VISIBLE);
        indexTxts[tag].setTextColor(ContextCompat.getColor(this, R.color.color_font_main));
    }

    /**
     * 时间设置点击事件逻辑
     */
    private View.OnClickListener timeClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int tag = (int) v.getTag();
            changeTimeStyle(tag);
            mApp.getDBMrg().addParam(DBaseConst.Trade_Speed, String.valueOf(tag));
            mApp.getDBMrg().save();
            THREAD_TIME = slowLabel[tag];
        }
    };

    /**
     * 更换时间显示样式
     *
     * @param tag 选择的下标
     */
    private void changeTimeStyle(int tag) {

        for (int i = 0; i < 5; i++) {
            timeImages[i].setVisibility(View.INVISIBLE);
            timeTxts[i].setTextColor(ContextCompat.getColor(this, R.color.color_game_normal));
        }
        timeImages[tag].setVisibility(View.VISIBLE);
        timeTxts[tag].setTextColor(ContextCompat.getColor(this, R.color.color_font_main));
    }

    /**
     * 暂停操作
     */
    protected void onPauseAction(boolean b) {
        Animation anim;
        if (b) {
            klineView.setCanClick(false);
            anim = AnimationUtils.loadAnimation(PageGamePlay.this,
                    R.anim.left_in);
            layoutPause.setVisibility(View.VISIBLE);
        } else {
            klineView.setCanClick(true);
            anim = AnimationUtils.loadAnimation(PageGamePlay.this,
                    R.anim.left_out);
            layoutPause.setVisibility(View.GONE);
        }
        layoutPause.setAnimation(anim);
        onShowPausePanel(-1);
    }

    /**
     * 暂停面板
     *
     * @param index 记录下标
     */
    protected void onShowPausePanel(int index) {

        for (int i = 0; i < 2; i++) {
            if (i == index) {
                pausePanels[i].setVisibility(View.VISIBLE);
            } else {
                pausePanels[i].setVisibility(View.GONE);
                btnInfo.setBackgroundResource(R.mipmap.ic_game_index_normal);
                btnTime.setBackgroundResource(R.mipmap.ic_game_time_normal);
            }
        }
    }

    /**
     * 加载股票数据
     */
    protected void loadStockHisData() {


        mAccount.reset();
        actions.clear();
        updateAccountInfo();

        readLocalFile();
        if (gameInfo.stock.tickets == null || gameInfo.stock.tickets.size() <= 0) {
            showToast("No data");
            klineView.setDataSource(null, mTask);
            return;
        }

        Collections.reverse(gameInfo.stock.tickets);

        AnalyzeManager.getInstance().analyzeIndex(gameInfo.stock, mTask);
        klineView.setDataSource(gameInfo.stock, mTask);
        klineView.setOffset(StockConst.STARTPOS);
        klineView.setDrawIndex(true);

        if (!TGApplication.vipUser) {
            //减除可玩局数
            //   SqliteActObject.getInstance(this).updateTimes(mApp.getUserId(), -1);
        }
        startGame();
    }

    /**
     * 下一关
     */
    private void nextGame() {

        if (TGApplication.vipUser) {
            loadStockHisData();
        } else {
            if (isCanNext()) {
                loadStockHisData();
            } else {
                noStarAction();
            }
        }
    }

    private boolean isCanNext() {

        ActObj accountEl = SqliteActObject.getInstance(this).getAccount(mApp.getUserId());
        return accountEl.useTimes >= 1;
    }

    private void noStarAction() {
        onBackAction();
    }

    /**
     * 计算系统买卖信号
     */
    @Override
    protected void onCalculateSystemBS() {

    }

    /**
     * 游戏结果
     */
    @Override
    protected void onGameResultAction(TraderAct account) {
        SqliteActObject sqliteAccObj = SqliteActObject.getInstance(this);
        //保存收益率
        sqliteAccObj.updateRise(mApp.getUserId(), account.getTotalValue());

        onShowGameResult();
        playSound(TradeSoundPool.GAMEOVER_RESULT);
    }

    /**
     * 显示成绩界面
     */
    @SuppressLint("DefaultLocale")
    protected void onShowGameResult() {

        if (gameInfo != null) {
            SqliteActObject.getInstance(PageGamePlay.this).updateIsUpload(mApp.getUserId(), "0");
            SqliteActObject.getInstance(this).updateGameId(mApp.getUserId(), "null");

            String startDate = klineView.getDataSource().tickets.get(StockConst.STARTPOS).date;
            String endDate = klineView.getDataSource().tickets.get(StockConst.MAXLEN - 1).date;

            Intent intent = new Intent(PageGamePlay.this, PagePpGameResult.class);
            intent.putExtra("stockCode", gameInfo.stock.code);
            intent.putExtra("stockName", gameInfo.stock.name);
            intent.putExtra("date", startDate + " - " + endDate);
            intent.putExtra("profit", mAccount.getTotalValue());
            intent.putExtra("profitRate", mAccount.getTotalRise() * 100);
            intent.putExtra("record", mAccount.getBsArr());
            startActivityForResult(intent, 0x100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0x100) {
            if (resultCode == 0x200) {
                onBackAction();
            } else if (resultCode == 0x201) {
                btnAnalyseExit.setVisibility(View.VISIBLE);
                ckPause.setClickable(false);
                btnBuy.setClickable(false);
                btnSell.setClickable(false);
                btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_pressed);
                btnSell.setBackgroundResource(R.mipmap.ic_game_sell_pressed);
                klineView.setReview(true);
            } else if (resultCode == 0x202) {
                ckPause.setClickable(true);
                btnBuy.setClickable(true);
                btnSell.setClickable(true);
                btnBuy.setBackgroundResource(R.mipmap.ic_game_buy_normal);
                btnSell.setBackgroundResource(R.mipmap.ic_game_sell_normal);
                nextGame();
            } else if (resultCode == 0x203) {
                onBackAction();
            }
        }
    }

    /**
     * 读取本地游戏地图数据并转化
     */
    private void readLocalFile() {
        InputStreamReader inputStreamReader;
        try {
            String[] names = this.getAssets().list("files");
            assert names != null;
            String fileName = names[new Random().nextInt(names.length)];
            byte[] results = uncompress(streamToBytes(getAssets().open("files/" + fileName)));
            String resultStr = new String(results);
            System.out.println("@@@@@@@@@" + resultStr);
            if (!StringUtils.isNull(resultStr)) {
                JSONObject jsonObject = new JSONObject(resultStr);
                gameInfo.parseJson(jsonObject);
            } else {
                showToast("There is a problem");
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("There is a problem");
        }
    }

    public static byte[] uncompress(byte[] inputByte) throws IOException {
        int len;
        Inflater inflater = new Inflater();
        inflater.setInput(inputByte);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] outByte = new byte[1024];
        try {
            while (!inflater.finished()) {
                // 解压缩并将解压缩后的内容输出到字节输出流bos中
                len = inflater.inflate(outByte);
                if (len == 0) {
                    break;
                }
                bos.write(outByte, 0, len);
            }
            inflater.end();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bos.close();
        }
        return bos.toByteArray();
    }

    public static byte[] streamToBytes(InputStream input) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        try {
            while (-1 != (n = input.read(buffer))) {
                output.write(buffer, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return output.toByteArray();
    }
}
